package com.hula.onion.book.server.spider.platforms.xiaozhulicai;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("xiaoZhuLiCaiSpider")
public class XiaoZhuLiCaiSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "http://www.xiaozhu158.com/user/login/dologin";

    /**
     * 验证码URL
     */
    private static final String CAPTCHA_URL = "http://www.xiaozhu158.com/index.php?g=api&m=checkcode&a=index&length=4&font_size=16&width=110&height=44&charset=1234567890&use_noise=1&use_curve=0&time=0.21963389380788145";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.xiaozhu158.com/user/index/index";

    @Autowired
    private XiaoZhuLiCaiSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {
        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), getHttpContext().getCookieStore());

        //2. 模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }

        if (spiderHelper.checkLogin(loginStr)) {
            //2.1 爬取用户详细信息
            String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
            //2.2 解析JSON
            return spiderHelper.parseAccountBalance(result);
        } else {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_URL;
    }

}

